package com.onec.service.unsafe.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * 不可以冲入的自旋锁
 */
public class SpinLock implements Lock {


  //
  private AtomicReference<Thread> owner = new AtomicReference<>();

  @Override
  public void lock() {
    Thread thread = Thread.currentThread();
    while (owner.compareAndSet(null, thread)) {
      // do something
      // 让出执行时间
      Thread.yield();
    }
  }

  @Override
  public void lockInterruptibly() throws InterruptedException {

  }

  @Override
  public boolean tryLock() {
    return false;
  }

  @Override
  public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
    return false;
  }

  @Override
  public void unlock() {

    // 如果可重入 增加技术器
    Thread thread = Thread.currentThread();
    while (thread == owner.get()) {
      owner.set(null);
    }
  }

  @Override
  public Condition newCondition() {
    return null;
  }
}
